package com.beiye.drivertransport.thematic.learning;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.bean.PayMentBean;
import com.beiye.drivertransport.bean.PaymentdecBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.Constants;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.UUID;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//新专项培训支付界面
public class NewPaymentActivity extends TwoBaseAty {

    ImageView img_payback;

    TextView tv_special;

    TextView tv_content;

    TextView tv_price;

    TextView tv_pay3;//购买

    TextView tv_money2;//差值

    private PopupWindow mUserPopWindow;
    private IWXAPI api;
    private String uqcSn;
    //private int qhCertSize;

    @Override
    public int getLayoutId() {
        return R.layout.activity_new_payment;
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_payback) {
            finish();
        } else if (id == R.id.tv_pay3) {//                if(Utils.isFastClicker())
//                {
//                    return;
//                }
            SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
            String idcNo = sp.getString("idcNo", "");
            int stId = sp.getInt("stId", 0);
            if (stId == 500001) {
                Bundle bundle = new Bundle();
                bundle.putString("idcNo", idcNo);
                startActivityForResult(ImprovingDataActivity.class, bundle, 0);
                return;
            }

            payment();//支付方法
        }
    }

    //支付方法
    public void payment() {
        SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        float price = sp.getFloat("price", 0);
        int stId = sp.getInt("stId", 0);
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        String phoneSign = getPhoneSign();//设备的唯一标识

        if (price > 0) {
            boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
            if (!isPaySupported) {
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(NewPaymentActivity.this);
                builder1.setMessage("该微信版本不支持微信支付或者未安装微信软件");
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ;
                    }
                });
                builder1.create().show();
                return;
            }
            Toast.makeText(NewPaymentActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
            tv_pay3.setEnabled(false);//微信支付
            new Login().getPayMentApp(userId, orgId, 2, stId, "APP", price, phoneSign, Constants.APP_ID, uqcSn, this, 1);
        } else {
            tv_pay3.setEnabled(false);//免费时余额支付
            new Login().getPayMentApp(userId, orgId, 3, stId, "APP", price, phoneSign, Constants.APP_ID, uqcSn, this, 4);
        }
    }

    /*****
     * 接受第二个Activity返回的数据时调用
     *
     * ****/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }
        // 根据返回码的不同，设置参数
        if (requestCode == 0) {
            if (resultCode == 1) {
                payment();//支付方法
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        new Login().getUser(userId, this, 2);//验证身份证
    }


    //    private void showpopwindow() {
//
//        View contentView = LayoutInflater.from(NewPaymentActivity.this).inflate(R.layout.checkuser_popwindowlayout, null);
//        mUserPopWindow = new PopupWindow(contentView,
//                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
//        EditText ed_id = (EditText) contentView.findViewById(R.id.ed_id);
//        mUserPopWindow.showAtLocation(ed_id, Gravity.CENTER, 0, 0);
//// 编辑框设置触摸监听
//        ed_id.setOnTouchListener(new View.OnTouchListener() {
//
//            @SuppressLint("ClickableViewAccessibility")
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (MotionEvent.ACTION_DOWN == event.getAction()) {
//                    ed_id.setCursorVisible(true);// 再次点击显示光标
//                }
//                return false;
//            }
//        });
//        TextView tv_idsave = (TextView) contentView.findViewById(R.id.tv_idsave);
//        tv_idsave.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // mUserPopWindow.dismiss();
//                String id = ed_id.getText().toString().trim();
//                if(id.equals(""))
//                {
//                    showToast("身份证不为空");
//                    return;
//                }
//                if (!IsIDcard(id)) {
//                    showToast("身份证无效");
//                    return;
//                }
//                LoginUserBean userInfo1 = UserManger.getUserInfo();
//                LoginUserBean.DataBean data = userInfo1.getData();
//                String userId = data.getUserId();
//                ImputUserID(userId,id);
//
//            }
//        });
//
//    }
//    private void ImputUserID(String userId, String id) {
//        showLoadingDialog("");
//        new Login().getImputUserID(userId, id,this,3);
//
//    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //     EventBus.getDefault().unregister(this);//反注册EventBus
        SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
    }


    @Override
    public void initData() {
        img_payback = (ImageView) findViewById(R.id.img_payback);
        tv_special = (TextView) findViewById(R.id.tv_pay4);
        tv_content = (TextView) findViewById(R.id.tv_content);
        tv_price = (TextView) findViewById(R.id.tv_money);
        tv_pay3 = (TextView)findViewById(R.id.tv_pay3);
        tv_money2 = (TextView)findViewById(R.id.tv_money2);
        //注册EventBus
        //    EventBus.getDefault().register(this);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);

    }

    /**
     * 将数据保留两位小数
     */
    private String getTwoDecimal(double num) {
        DecimalFormat dFormat = new DecimalFormat("#0.00");
        String yearString = dFormat.format(num);
        return yearString;
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
            int paytag = sp.getInt("paytag", 0);
            PayMentBean payMentBean = JSON.parseObject(result, PayMentBean.class);
            String msg = payMentBean.getMsg();//支付订单系列号
            SharedPreferences sp1 = getSharedPreferences("msg", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit1 = sp1.edit();
            edit1.putString("msg", msg);
            edit1.putInt("paytag", paytag);
            edit1.commit();
            PayMentBean.DataBean paydata = payMentBean.getData();//微信服务器返回的结果
            if (paydata != null) {
                api.registerApp(Constants.APP_ID);
                PayReq req = new PayReq();
                req.appId = Constants.APP_ID;
                req.packageValue = "Sign=WXPay";
                req.partnerId = paydata.getPartnerid();
                req.prepayId = paydata.getPrepayid();
                req.nonceStr = paydata.getNoncestr();
                req.timeStamp = paydata.getTimestamp();
                req.sign = paydata.getSign();
                api.sendReq(req);
                finish();
            }
            tv_pay3.setEnabled(true);
        } else if (what == 2) {
            MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
            MineUseBean.DataBean data = mineUseBean.getData();
            String idcNo = data.getIdcNo();
            if (idcNo == null) {
                SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("idcNo", "");
                edit.commit();
            } else {
                SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("idcNo", idcNo);
                edit.commit();
            }
        }
//        else if(what==3)
//        {
//            dismissLoadingDialog();
//            mUserPopWindow.dismiss();
//            LoginUserBean userInfo = UserManger.getUserInfo();
//            LoginUserBean.DataBean data = userInfo.getData();
//            String userId = data.getUserId();
//            new Login().getUser(userId,this,2);   //再次验证是否有身份证信息判断按钮是否为灰
//            payment();
//
//        }
        else if (what == 4) {
            SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
            int paytag = sp.getInt("paytag", 0);
            if (paytag == 1) {

                EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_12));
                finish();

            } else if (paytag == 2) {
                EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_13));
                finish();

            } else if (paytag == 3) {
                EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_14));
                finish();
            }


        }
        super.onSuccess(result, call, response, what);
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        if (what == 1) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                    //设置你的操作事项
                }
            });
            builder1.create().show();


        }
//         else if(what==3)
//        {
//            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//            String msg = checkBean.getMsg();
//            dismissLoadingDialog();
//            showToast(msg);
//
//
//        }
        else if (what == 4) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            int code = checkBean.getCode();
            if (code == 1881)//该专项培训免费或者已付费
            {
                SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
                int paytag = sp.getInt("paytag", 0);
                if (paytag == 1) {

                    EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_12));
                    finish();

                } else if (paytag == 2) {
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_13));
                    finish();

                } else if (paytag == 3) {
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_14));
                    finish();
                }

            } else {
                String msg = checkBean.getMsg();
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                builder1.setMessage(msg);
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ;
                        //设置你的操作事项
                    }
                });
                builder1.create().show();
            }
        }
        super.onError(result, call, response, what);
    }

    @Override
    public void requestData() {
        Bundle bundle = getIntent().getExtras();
        int stId = bundle.getInt("stId");
        String orgId = bundle.getString("orgId");
        String stName = bundle.getString("stName");
        int paytag = bundle.getInt("paytag");
        float price = bundle.getFloat("price");
        uqcSn = bundle.getString("uqcSn");

        /*if(stId==630011){
            qhCertSize=bundle.getInt("qhCertSize");
            price=qhCertSize*price;
        }*/

        String twoDecimal = getTwoDecimal(price);
        tv_price.setText(twoDecimal + "元");

        SharedPreferences sp = getSharedPreferences("NewPaymentActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("orgId", orgId);
        edit.putInt("stId", stId);
        edit.putInt("paytag", paytag);
        edit.putFloat("price", price);
        edit.commit();
        if (stName == null || stName.equals("")) {
            tv_special.setText("");
        } else {
            tv_special.setText(stName);
        }

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        showLoadingDialog("");
        new Login().getUser(userId, this, 2);//验证身份证

        //查询购买专项培训说明
        RequestParams params = new RequestParams(AppInterfaceConfig.BASE_URL + "course/specTrain/findStDesc/" + stId);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                PaymentdecBean paymentdecBean = JSON.parseObject(result, PaymentdecBean.class);
                String desData = paymentdecBean.getData();
                if (desData == null) {
                    if (stName.equals("")) {
                        tv_content.setText("");
                    } else {
                        tv_content.setText("本课程学习内容仅用于" + stName + "，如需购买其他学习内容，请返回点击其他学习页面。");
                    }
                } else {
                    tv_content.setText(desData);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("网络连接错误");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    //获取手机的唯一标识
    @SuppressLint("MissingPermission")
    public String getPhoneSign() {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            // IMEI（imei）
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (!TextUtils.isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!TextUtils.isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID();
            if (!TextUtils.isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID());
        }
        return deviceId.toString();
    }

    /**
     * 得到全局唯一UUID
     */
    private String uuid;

    public String getUUID() {
        SharedPreferences mShare = getSharedPreferences("uuid", MODE_PRIVATE);
        if (mShare != null) {
            uuid = mShare.getString("uuid", "");
        }
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString();
            mShare.edit().putString("uuid", uuid).commit();
        }
        return uuid;
    }
    /**
     * 验证输入身份证号
     *
     * @param
     * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
     */
//    public  boolean IsIDcard(String str) {
//        String regex = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx]$)";
//        return match(regex, str);
//    }
    /**
     * @param regex
     * 正则表达式字符串
     * @param str
     * 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
//    private  boolean match(String regex, String str) {
//        Pattern pattern = Pattern.compile(regex);
//        Matcher matcher = pattern.matcher(str);
//        return matcher.matches();
//    }
}
